package me.dqn.noway.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import me.dqn.noway.R;
import me.dqn.noway.adapter.MainRecycleViewAdapter;
import me.dqn.noway.bean.NoWayContext;
import me.dqn.noway.bean.PasswordInformation;
import me.dqn.noway.bean.PasswordUser;
import me.dqn.noway.precenter.MyPresenter;
import me.dqn.noway.window.AddPopWindow;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    public static Handler handler;
    public RecyclerView mainRecycleView;
    MyPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         *
         *  set presenter MVP pattern
         */
        setPresenter();
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        addInfoPop(fab);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        // get RecycleView
        setupRecycleView();
        // handler
        setupHandler();
        //init
        init();

    }

    /**
     * pop a window to add new password information
     *
     * @param fab
     */
    private void addInfoPop(FloatingActionButton fab) {
        fab.setOnClickListener(view -> {
            if (NoWayContext.getINSTANCE().getPasswordUser() == null) {
                NoWayContext.getINSTANCE().getMyPresenter().toastMessages("登陆后再操作~", Toast.LENGTH_SHORT);
            } else {
                View popView = LayoutInflater.from(this).inflate(R.layout.add_password_info_pop, null);
                new AddPopWindow(popView);
            }
        });
    }

    private void init() {
        presenter.getAllInfos();
    }

    private void setupRecycleView() {
        this.mainRecycleView = this.findViewById(R.id.main_recycle_view);
        this.mainRecycleView.setAdapter(new MainRecycleViewAdapter(this, presenter));
        this.mainRecycleView.setLayoutManager(new LinearLayoutManager(this));
        this.mainRecycleView.setItemAnimator(new DefaultItemAnimator());
    }

    /**
     * handler
     */
    private void setupHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MyPresenter.UPDATE_VIEW:
                        List<PasswordInformation> passwordInformationList = (List<PasswordInformation>) msg.obj;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            passwordInformationList.sort((o1, o2) -> o2.getId() - o1.getId());
                        }
                        updateMainRecycleView(passwordInformationList);
                        break;
                    case MyPresenter.GET_DATA_FAILED:
                        Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        break;
                    case MyPresenter.ADD_INFO_FAILED:
                        Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                        break;
                    case MyPresenter.POP_MESSAGE:
                        Bundle bundle = msg.getData();
                        Toast.makeText(MainActivity.this, bundle.getString("msg"), bundle.getInt("time")).show();
                        break;
                }
            }
        };
    }

    /**
     * presenter
     */
    private void setPresenter() {
        presenter = new MyPresenter();
        presenter.setActivity(this);
        NoWayContext.getINSTANCE().setMyPresenter(presenter);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            // ask for quit.
            popQiutWindow();
        }
    }

    /**
     * 退出窗口
     */
    private void popQiutWindow() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.is_quit);
        // 退出
        NoWayContext.getINSTANCE().setPasswordUser(null);
        builder.setTitle(R.string.login);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            Log.i("quit dialog", "sure");
            presenter.quit();
            MainActivity.super.onBackPressed();
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> {
            Log.i("quit dialog", "cancel");
            dialog.dismiss();
        });
        builder.show();
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_manage:
                presenter.getAllInfos();
                break;
            case R.id.nav_send:
                break;
        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * 更新列表，在获取到数据后
     *
     * @param informations
     */
    public void updateMainRecycleView(List<PasswordInformation> informations) {
        MainRecycleViewAdapter adapter = (MainRecycleViewAdapter) mainRecycleView.getAdapter();
        adapter.passwordInformations = informations;
        adapter.notifyDataSetChanged();
    }

    /**
     * 登陆的窗口
     */
    public void popLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 获得弹窗的view
        View dialoagView = LayoutInflater.from(this).inflate(R.layout.login_pop, null, false);
        EditText account = dialoagView.findViewById(R.id.id_login_username);
        EditText password = dialoagView.findViewById(R.id.id_login_password);
        // 添加进builder
        builder.setView(dialoagView);
        builder.setTitle(R.string.login);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            PasswordUser passwordUser = new PasswordUser();
            passwordUser.setDecryptKey(password.getText().toString());
            passwordUser.setUsername(account.getText().toString());
            NoWayContext.getINSTANCE().setPasswordUser(passwordUser);
            TextView title = this.findViewById(R.id.id_nav_title);
            title.setText(passwordUser.getUsername());
            presenter.getAllInfos();
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> {
            account.getText().clear();
            password.getText().clear();
        });
        builder.show();
    }
}
